import { app, BrowserWindow, ipcMain, dialog, protocol } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import ffmpeg from 'fluent-ffmpeg'
import ffmpegPath from '@ffmpeg-installer/ffmpeg'
import ffprobePath from '@ffprobe-installer/ffprobe'
import fs from 'fs/promises'
import path from 'path'
import Store from 'electron-store'

// 创建 store 实例
const store = new Store()

// 设置 ffmpeg
ffmpeg.setFfmpegPath(ffmpegPath.path)
ffmpeg.setFfprobePath(ffprobePath.path)

// 支持的媒体类型
const MEDIA_EXTENSIONS = {
  image: ['.jpg', '.jpeg', '.png', '.gif', '.webp'],
  video: ['.mp4', '.webm', '.mkv', '.avi', '.mov']
}

// 缩略图缓存目录
const THUMBNAIL_DIR = path.join(app.getPath('userData'), 'thumbnails')

// 创建主窗口
function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    show: false,
    autoHideMenuBar: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      webSecurity: false,
      devTools: true,
      webPreferences: {
        contextIsolation: true,
        nodeIntegration: false,
        webSecurity: false,
        allowRunningInsecureContent: true
      }
    }
  })

  // 设置 CSP
  mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': ["default-src 'self' 'unsafe-inline' 'unsafe-eval' data: media: blob:"]
      }
    })
  })

  // 添加快捷键支持
  mainWindow.webContents.on('before-input-event', (event, input) => {
    if (input.key === 'F12') {
      mainWindow.webContents.toggleDevTools()
      event.preventDefault()
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// 生成视频缩略图
async function generateThumbnail(videoPath) {
  try {
    await fs.mkdir(THUMBNAIL_DIR, { recursive: true })
    const videoFileName = path.basename(videoPath)
    const thumbnailName = `${videoFileName}_thumb.jpg`
    const thumbnailPath = path.join(THUMBNAIL_DIR, thumbnailName)

    // 检查缩略图是否已存在
    try {
      await fs.access(thumbnailPath)
      return thumbnailPath
    } catch {
      // 缩略图不存在，继续生成
    }

    return new Promise((resolve, reject) => {
      // 先获取视频信息
      ffmpeg.ffprobe(videoPath, (err, metadata) => {
        if (err) {
          console.error('Failed to probe video:', err)
          resolve(null)
          return
        }

        // 获取视频流信息
        const videoStream = metadata.streams.find(s => s.codec_type === 'video')
        if (!videoStream) {
          console.error('No video stream found')
          resolve(null)
          return
        }

        // 获取视频的实际宽高
        let width = videoStream.width
        let height = videoStream.height

        // 考虑视频旋转角度
        const rotation = videoStream.rotation || videoStream.tags?.rotate || 0
        if (Math.abs(rotation) === 90 || Math.abs(rotation) === 270) {
          [width, height] = [height, width]
        }

        // 计算缩略图尺寸，保持原始比例
        // 目标：生成一个最大边长为1080像素的缩略图
        const MAX_SIZE = 1080
        let targetWidth, targetHeight

        if (width >= height) {
          targetWidth = Math.min(width, MAX_SIZE)
          targetHeight = Math.round(targetWidth * (height / width))
        } else {
          targetHeight = Math.min(height, MAX_SIZE)
          targetWidth = Math.round(targetHeight * (width / height))
        }

        // 生成缩略图
        ffmpeg(videoPath)
          .screenshots({
            count: 1,
            timestamps: ['10%'], // 从视频 10% 处截图，避免黑屏
            folder: THUMBNAIL_DIR,
            filename: thumbnailName,
            size: `${targetWidth}x${targetHeight}`,
            quality: 100 // 提高 JPEG 质量 (1-100)
          })
          .outputOptions([
            '-frames:v 1',
            '-q:v 2' // 降低压缩率，提高质量 (2-31，数字越小质量越好)
          ])
          .on('end', () => {
            resolve(thumbnailPath)
          })
          .on('error', (err) => {
            console.error('Thumbnail generation failed:', err)
            resolve(null)
          })
      })
    })
  } catch (error) {
    console.error('Thumbnail error:', error)
    return null
  }
}

// 获取文件类型
function getFileType(filePath) {
  const ext = path.extname(filePath).toLowerCase()
  if (MEDIA_EXTENSIONS.image.includes(ext)) return 'image'
  if (MEDIA_EXTENSIONS.video.includes(ext)) return 'video'
  return null
}

// 应用初始化
app.whenReady().then(() => {
  // 注册媒体文件协议
  protocol.registerFileProtocol('media', (request, callback) => {
    try {
      const filePath = decodeURIComponent(request.url.slice('media://'.length))
      const normalizedPath = path.normalize(filePath)
      
      console.log('Media protocol handler:', {
        url: request.url,
        filePath: filePath,
        normalizedPath: normalizedPath
      })

      callback({
        path: normalizedPath,
        headers: {
          'Access-Control-Allow-Origin': '*'
        }
      })
    } catch (error) {
      console.error('Protocol error:', error)
      callback({ error: -2 })
    }
  })

  // 注册缩略图协议
  protocol.registerFileProtocol('thumbnails', (request, callback) => {
    try {
      const fileName = decodeURIComponent(request.url.slice('thumbnails://'.length))
      const filePath = path.join(THUMBNAIL_DIR, fileName)
      
      console.log('Thumbnail protocol handler:', {
        url: request.url,
        fileName,
        filePath
      })

      callback({
        path: filePath,
        headers: {
          'Content-Type': 'image/jpeg'
        }
      })
    } catch (error) {
      console.error('Thumbnail protocol error:', error)
      callback({ error: -2 })
    }
  })

  // 选择文件夹
  ipcMain.handle('select-folder', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory']
    })
    return result.canceled ? null : result.filePaths[0]
  })

  // 读取媒体文件
  ipcMain.handle('read-media-files', async (_, folderPath, page = 1, pageSize = 50) => {
    try {
      const files = await fs.readdir(folderPath)
      const mediaFiles = []

      // 获取所有媒体文件的信息
      for (const file of files) {
        const filePath = path.join(folderPath, file)
        const stats = await fs.stat(filePath)
        
        if (stats.isFile()) {
          const type = getFileType(filePath)
          if (type) {
            mediaFiles.push({
              name: file,
              path: filePath,
              type,
              size: stats.size,
              modifiedTime: stats.mtime.getTime() // 转换为时间戳
            })
          }
        }
      }

      // 按修改时间降序排序（最新的在前面）
      mediaFiles.sort((a, b) => b.modifiedTime - a.modifiedTime)

      const start = (page - 1) * pageSize
      const end = start + pageSize
      return {
        files: mediaFiles.slice(start, end),
        total: mediaFiles.length,
        hasMore: end < mediaFiles.length
      }
    } catch (error) {
      console.error('Read media files error:', error)
      throw error
    }
  })

  // 生成缩略图
  ipcMain.handle('generate-thumbnail', async (_, videoPath) => {
    return await generateThumbnail(videoPath)
  })

  // 移动文件
  ipcMain.handle('move-files', async (_, files, targetDir) => {
    try {
      for (const file of files) {
        const targetPath = path.join(targetDir, path.basename(file))
        await fs.rename(file, targetPath)
      }
      return true
    } catch (error) {
      console.error('Move files error:', error)
      throw error
    }
  })

  // 清除缩略图缓存
  ipcMain.handle('clear-thumbnails', async () => {
    try {
      // 确保目录存在
      try {
        await fs.access(THUMBNAIL_DIR)
      } catch {
        // 目录不存在，直接返回成功
        return true
      }

      // 读取目录中的所有文件
      const files = await fs.readdir(THUMBNAIL_DIR)
      
      // 删除所有文件
      for (const file of files) {
        const filePath = path.join(THUMBNAIL_DIR, file)
        await fs.unlink(filePath)
      }

      // 删除目录本身
      await fs.rmdir(THUMBNAIL_DIR)
      
      return true
    } catch (error) {
      console.error('Clear thumbnails error:', error)
      throw error
    }
  })

  // 获取子文件夹
  ipcMain.handle('get-sub-folders', async (_, folderPath) => {
    try {
      const items = await fs.readdir(folderPath, { withFileTypes: true })
      const folders = []

      for (const item of items) {
        if (item.isDirectory()) {
          const fullPath = path.join(folderPath, item.name)
          folders.push({
            name: item.name,
            path: fullPath
          })
        }
      }

      // 按名称排序
      folders.sort((a, b) => a.name.localeCompare(b.name))
      return folders
    } catch (error) {
      console.error('Get subfolders error:', error)
      throw error
    }
  })

  // 创建文件夹
  ipcMain.handle('create-folder', async (_, parentPath, name) => {
    try {
      const newPath = path.join(parentPath, name)
      await fs.mkdir(newPath)
      return newPath
    } catch (error) {
      console.error('Create folder error:', error)
      throw error
    }
  })

  // 重命名文件夹
  ipcMain.handle('rename-folder', async (_, oldPath, newName) => {
    try {
      const parentPath = path.dirname(oldPath)
      const newPath = path.join(parentPath, newName)
      await fs.rename(oldPath, newPath)
      return newPath
    } catch (error) {
      console.error('Rename folder error:', error)
      throw error
    }
  })

  // 删除文件夹
  ipcMain.handle('delete-folder', async (_, folderPath) => {
    try {
      await fs.rm(folderPath, { recursive: true })
      return true
    } catch (error) {
      console.error('Delete folder error:', error)
      throw error
    }
  })

  // 保存路径
  ipcMain.handle('save-paths', async (_, { sourceFolder, targetFolder }) => {
    try {
      store.set('lastSourceFolder', sourceFolder)
      store.set('lastTargetFolder', targetFolder)
      return true
    } catch (error) {
      console.error('Save paths error:', error)
      throw error
    }
  })

  // 获取保存的路径
  ipcMain.handle('get-saved-paths', async () => {
    try {
      return {
        sourceFolder: store.get('lastSourceFolder', ''),
        targetFolder: store.get('lastTargetFolder', '')
      }
    } catch (error) {
      console.error('Get saved paths error:', error)
      throw error
    }
  })

  createWindow()
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
